<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="1title:浅析spring   Spring是一种轻量级框架，旨在提高开发人员的开发效率以及系统的可维护性。  spring的好处：1.降低组件之间的耦合度，实现软件各层之间的解耦2.可以使容器提供众多服务如事务管理消息服务处理等等3.容器提供单例模式的支持，开发人员不需要编写实现代码4.提供AOP技术，利用它容易实现权限拦截、运行期监控等功能5.容器提供众多的辅助类，集成各种优秀框架，加快应">
<meta property="og:type" content="article">
<meta property="og:title" content="浅析spring">
<meta property="og:url" content="https://www.suichen.top/2020/03/20/%E6%B5%85%E6%9E%90spring/index.html">
<meta property="og:site_name" content="随尘的博客">
<meta property="og:description" content="1title:浅析spring   Spring是一种轻量级框架，旨在提高开发人员的开发效率以及系统的可维护性。  spring的好处：1.降低组件之间的耦合度，实现软件各层之间的解耦2.可以使容器提供众多服务如事务管理消息服务处理等等3.容器提供单例模式的支持，开发人员不需要编写实现代码4.提供AOP技术，利用它容易实现权限拦截、运行期监控等功能5.容器提供众多的辅助类，集成各种优秀框架，加快应">
<meta property="og:image" content="https://img2018.cnblogs.com/blog/842514/201906/842514-20190611160935478-279758854.png">
<meta property="og:image" content="https://img2018.cnblogs.com/blog/842514/201906/842514-20190611220522364-1747090465.png">
<meta property="og:image" content="https://img2018.cnblogs.com/blog/842514/201906/842514-20190611220552139-1446928813.png">
<meta property="og:image" content="https://img2018.cnblogs.com/blog/842514/201906/842514-20190612121947431-1483101551.png">
<meta property="article:published_time" content="2020-03-20T09:06:26.992Z">
<meta property="article:modified_time" content="2020-04-15T02:45:11.316Z">
<meta property="article:author" content="suichen">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img2018.cnblogs.com/blog/842514/201906/842514-20190611160935478-279758854.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.suichen.top/2020/03/20/浅析spring/"/>





  <title>浅析spring | 随尘的博客</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">随尘的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.suichen.top/2020/03/20/%E6%B5%85%E6%9E%90spring/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="suichen">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="随尘的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">浅析spring</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-03-20T17:06:26+08:00">
                2020-03-20
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">title:浅析spring</span><br></pre></td></tr></table></figure>

<p> Spring是一种轻量级框架，旨在提高开发人员的开发效率以及系统的可维护性。 </p>
<h3 id="spring的好处："><a href="#spring的好处：" class="headerlink" title="spring的好处："></a>spring的好处：</h3><p>1.降低组件之间的耦合度，实现软件各层之间的解耦<br>2.可以使容器提供众多服务如事务管理消息服务处理等等<br>3.容器提供单例模式的支持，开发人员不需要编写实现代码<br>4.提供AOP技术，利用它容易实现权限拦截、运行期监控等功能<br>5.容器提供众多的辅助类，集成各种优秀框架，加快应用的开发</p>
<h3 id="1-Spring框架"><a href="#1-Spring框架" class="headerlink" title="1.Spring框架"></a>1.Spring框架</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">我们一般说的Spring框架就是Spring Framework，它是很多模块的集合，使用这些模块可以很方便地协助我们进行开发。这些模块是核心容器、数据访问&#x2F;集成、Web、AOP（面向切面编程）、工具、消息和测试模块。比如Core Container中的Core组件是Spring所有组件的核心，Beans组件和Context组件是实现IOC和DI的基础，AOP组件用来实现面向切面编程。</span><br></pre></td></tr></table></figure>

<p><img src="https://img2018.cnblogs.com/blog/842514/201906/842514-20190611160935478-279758854.png" alt="img"></p>
<p>Spring Core：基础，可以说Spring其他所有的功能都依赖于该类库。主要提供IOC和DI功能。</p>
<p>Spring Aspects：该模块为与AspectJ的集成提供支持。</p>
<p>Spring AOP：提供面向切面的编程实现。</p>
<p>Spring JDBC：Java数据库连接。</p>
<p>Spring JMS：Java消息服务。</p>
<p>Spring ORM：用于支持Hibernate等ORM工具。</p>
<p>Spring Web：为创建Web应用程序提供支持。</p>
<p>Spring Test：提供了对JUnit和TestNG测试的支持。</p>
<h4 id="Spring官网（https-spring-io-）列出的Spring的6个特征："><a href="#Spring官网（https-spring-io-）列出的Spring的6个特征：" class="headerlink" title="Spring官网（https://spring.io/）列出的Spring的6个特征："></a>Spring官网（<a href="https://spring.io/）列出的Spring的6个特征：" target="_blank" rel="noopener">https://spring.io/）列出的Spring的6个特征：</a></h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">核心技术：依赖注入（DI），AOP，事件（Events），资源，i18n，验证，数据绑定，类型转换，SpEL。</span><br><span class="line"></span><br><span class="line">测试：模拟对象，TestContext框架，Spring MVC测试，WebTestClient。</span><br><span class="line"></span><br><span class="line">数据访问：事务，DAO支持，JDBC，ORM，编组XML。</span><br><span class="line"></span><br><span class="line">Web支持：Spring MVC和Spring WebFlux Web框架。</span><br><span class="line"></span><br><span class="line">集成：远程处理，JMS，JCA，JMX，电子邮件，任务，调度，缓存。</span><br><span class="line"></span><br><span class="line">语言：Kotlin，Groovy，动态语言。</span><br></pre></td></tr></table></figure>

<h4 id="spring框架中使用的设计模式"><a href="#spring框架中使用的设计模式" class="headerlink" title="spring框架中使用的设计模式"></a>spring框架中使用的设计模式</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">1.工厂设计模式：Spring使用工厂模式通过BeanFactory和ApplicationContext创建bean对象。</span><br><span class="line"></span><br><span class="line">2.代理设计模式：Spring AOP功能的实现。</span><br><span class="line"></span><br><span class="line">3.单例设计模式：Spring中的bean默认都是单例的。</span><br><span class="line"></span><br><span class="line">4.模板方法模式：Spring中的jdbcTemplate、hibernateTemplate等以Template结尾的对数据库操作的类，它们就使用到了模板模式。</span><br><span class="line"></span><br><span class="line">5.包装器设计模式：我们的项目需要连接多个数据库，而且不同的客户在每次访问中根据需要会去访问不同的数据库。这种模式让我们可以根据客户的需求能够动态切换不同的数据源。</span><br><span class="line"></span><br><span class="line">6.观察者模式：Spring事件驱动模型就是观察者模式很经典的一个应用。</span><br><span class="line"></span><br><span class="line">7.适配器模式：Spring AOP的增强或通知（Advice）使用到了适配器模式、Spring MVC中也是用到了适配器模式适配Controller。</span><br></pre></td></tr></table></figure>

<h3 id="2-IOC与DI"><a href="#2-IOC与DI" class="headerlink" title="2.IOC与DI"></a>2.IOC与DI</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">IOC：控制反转，即OC容器负责实例化、定位、配置应用程序中的对象及建立这些对象间的依赖。交由Spring容器统一进行管理，从而实现松耦合。底层用工厂模式</span><br><span class="line">实现原理：使用反射机制+XML技术</span><br><span class="line">流程：启动tomcat容器-&gt;初始化spring容器-&gt;获取扫描包下的所有class文件-&gt;解析class中的注解信息-&gt;封装类反射后实例化对象-&gt;本地调用某个bean中的方法-&gt;以beanId,bean实例化类对象形式保存集合—&gt;getBean-&gt;bean的实例化对象-&gt;bean的具体方法及执行结果</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DI：Dependency Injection 依赖注入，控制反转的常见的方式，还有一种是依赖查找。</span><br></pre></td></tr></table></figure>

<p>1.注入方式：</p>
<p>​    1）set方式注入:需要set方法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id&#x3D;&quot;mainboard&quot; class&#x3D;&quot;com.spring.service.pc.Ipml.InterBoard&quot;&gt;</span><br><span class="line">    &lt;property name&#x3D;&quot;cpu&quot;&gt;</span><br><span class="line">        &lt;bean class&#x3D;&quot;com.spring.service.pc.Ipml.InterCpu&quot;&gt;&lt;&#x2F;bean&gt;</span><br><span class="line">    &lt;&#x2F;property&gt;</span><br><span class="line">    &lt;property name&#x3D;&quot;ram&quot;&gt;</span><br><span class="line">        &lt;bean class&#x3D;&quot;com.spring.service.pc.Ipml.KingstoneRam&quot;&gt;&lt;&#x2F;bean&gt;</span><br><span class="line">    &lt;&#x2F;property&gt;</span><br><span class="line">&lt;&#x2F;bean&gt;</span><br></pre></td></tr></table></figure>

<p>2）构造器注入： 需生产带参数的构造方法 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">使用方式：</span><br><span class="line">第一，在类中，不用为属性设置setter方法，但是需要生成该类带参的构造方法。</span><br><span class="line">第二，在配置文件中配置该类的bean，并配置构造器，在配置构造器中用到了&lt;constructor-arg&gt;节点，该节点有四个属性：</span><br><span class="line">· index是索引，指定注入的属性，从0开始；</span><br><span class="line">· type是指该属性所对应的类型；</span><br><span class="line">· ref 是指引用的依赖对象；</span><br><span class="line">· value 当注入的不是依赖对象，而是基本数据类型时，就用value；</span><br></pre></td></tr></table></figure>

<h3 id="3-AOP"><a href="#3-AOP" class="headerlink" title="3.AOP"></a>3.AOP</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">AOP：面向切面编程，扩展功能不修改源代码实现，采用横向抽取机制，取代传统的纵向继承体系重复性代码（性能监视，事务管理，安全检查，缓存），底层用代理模式</span><br><span class="line">名词解释：</span><br><span class="line">JoinPoint(连接点):目标对象中,所有可以增强的方法，就是spring允许你是通知（Advice）的地方，那可就真多了，基本每个方法的前、后（两者都有也行），或抛出异常是时都可以是连接点，spring只支持方法连接点。</span><br><span class="line"></span><br><span class="line">Pointcut(切入点):目标对象中,已经被增强的方法。调用这几个方法之前、之后或者抛出异常时干点什么，那么就用切入点来定义这几个方法。</span><br><span class="line"></span><br><span class="line">Advice(通知&#x2F;增强) :增强方法的代码、想要的功能。</span><br><span class="line"></span><br><span class="line">Target(目标对象):被代理对象，被通知的对象，被增强的类对象。</span><br><span class="line"></span><br><span class="line">Weaving(织入):将通知应用到连接点形成切入点的过程</span><br><span class="line"></span><br><span class="line">Proxy(代理):将通知织入到目标对象之后形成的代理对象</span><br><span class="line"></span><br><span class="line">aspect(切面):切入点+通知————通知(Advice)说明了干什么的内容(即方法体代码)和什么时候干（什么时候通过方法名中的before，after，around等就能知道），二切入点说明了在哪干（指定到底是哪个方法），切点表达式等定义。</span><br><span class="line"></span><br><span class="line">注解解释</span><br><span class="line"></span><br><span class="line">@Before 前置通知（Before advice） ：在某连接点（JoinPoint）——核心代码（类或者方法）之前执行的通知，但这个通知不能阻止连接点前的执行。为啥不能阻止线程进入核心代码呢？因为@Before注解的方法入参不能传ProceedingJoinPoint，而只能传入JoinPoint。要知道从aop走到核心代码就是通过调用ProceedingJionPoint的proceed()方法。而JoinPoint没有这个方法。 </span><br><span class="line">这里牵扯区别这两个类：Proceedingjoinpoint 继承了 JoinPoint 。是在JoinPoint的基础上暴露出 proceed 这个方法。proceed很重要，这个是aop代理链执行的方法。暴露出这个方法，就能支持 aop:around 这种切面（而其他的几种切面只需要用到JoinPoint，这跟切面类型有关）， 能决定是否走代理链还是走自己拦截的其他逻辑。建议看一下 JdkDynamicAopProxy的invoke方法，了解一下代理链的执行原理。这样你就能明白 proceed方法的重要性。</span><br><span class="line"></span><br><span class="line">@After 后通知（After advice） ：当某连接点退出的时候执行的通知（不论是正常返回还是异常退出）。</span><br><span class="line"></span><br><span class="line">@AfterReturning 返回后通知（After return advice） ：在某连接点正常完成后执行的通知，不包括抛出异常的情况。</span><br><span class="line"></span><br><span class="line">@Around 环绕通知（Around advice） ：包围一个连接点的通知，类似Web中Servlet规范中的Filter的doFilter方法。可以在方法的调用前后完成自定义的行为，也可以选择不执行。这时aop的最重要的，最常用的注解。用这个注解的方法入参传的是ProceedingJionPoint pjp，可以决定当前线程能否进入核心方法中——通过调用pjp.proceed();</span><br><span class="line"></span><br><span class="line">@AfterThrowing 抛出异常后通知（After throwing advice） ： 在方法抛出异常退出时执行的通知。</span><br></pre></td></tr></table></figure>

<p>两种种实现方式：</p>
<p>1）基于xml配置的实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"> 1 &lt;!-- 使用xml配置aop --&gt;  </span><br><span class="line"> 2 &lt;!-- 强制使用cglib代理，如果不设置，将默认使用jdk的代理，但是jdk的代理是基于接口的 --&gt;  </span><br><span class="line"> 3 &lt;aop:config proxy-target-class&#x3D;&quot;true&quot; &#x2F;&gt;    </span><br><span class="line"> 4 &lt;aop:config&gt;  </span><br><span class="line"> 5 &lt;!--定义切面--&gt;  </span><br><span class="line"> 6     &lt;aop:aspect id&#x3D;&quot;logAspect&quot; ref&#x3D;&quot;logInterceptor&quot;&gt;  </span><br><span class="line"> 7     &lt;!-- 定义切入点 (配置在com.gray.user.controller下所有的类在调用之前都会被拦截)--&gt;  </span><br><span class="line"> 8     &lt;aop:pointcut expression&#x3D;&quot;execution(* com.gray.user.controller.*.*(..))&quot; id&#x3D;&quot;logPointCut&quot;&#x2F;&gt;  </span><br><span class="line"> 9     &lt;!--方法执行之前被调用执行的--&gt;  </span><br><span class="line">10     &lt;aop:before method&#x3D;&quot;before&quot; pointcut-ref&#x3D;&quot;logPointCut&quot;&#x2F;&gt;&lt;!--一个切入点的引用--&gt;  </span><br><span class="line">11     &lt;aop:after method&#x3D;&quot;after&quot; pointcut-ref&#x3D;&quot;logPointCut&quot;&#x2F;&gt;&lt;!--一个切入点的引用--&gt;  </span><br><span class="line">12     &lt;&#x2F;aop:aspect&gt;  </span><br><span class="line">13 &lt;&#x2F;aop:config&gt;</span><br></pre></td></tr></table></figure>

<p>2)基于注解的实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">@Aspect  </span><br><span class="line">@Component  </span><br><span class="line">public class LogInterceptor &#123;  </span><br><span class="line">    private final Logger logger &#x3D; LoggerFactory.getLogger(LogInterceptor.class);  </span><br><span class="line">    @Before(value &#x3D; &quot;execution(* com.gray.user.controller.*.*(..))&quot;)  </span><br><span class="line">    public void before()&#123;  </span><br><span class="line">        logger.info(&quot;login start!&quot;);  </span><br><span class="line">    &#125;  </span><br><span class="line">    @After(value &#x3D; &quot;execution(* com.gray.user.controller.*.*(..))&quot;)  </span><br><span class="line">    public void after()&#123;  </span><br><span class="line">        logger.info(&quot;login end!&quot;);  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="4-spring中Bean的部分知识"><a href="#4-spring中Bean的部分知识" class="headerlink" title="4.spring中Bean的部分知识"></a>4.spring中Bean的部分知识</h3><p>1）bean的生命周期</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">1.Bean容器找到配置文件中Spring Bean的定义。</span><br><span class="line"></span><br><span class="line">2.Bean容器利用Java Reflection API创建一个Bean的实例。</span><br><span class="line"></span><br><span class="line">3.如果涉及到一些属性值，利用set()方法设置一些属性值。</span><br><span class="line"></span><br><span class="line">4.如果Bean实现了BeanNameAware接口，调用setBeanName()方法，传入Bean的名字。</span><br><span class="line"></span><br><span class="line">5.如果Bean实现了BeanClassLoaderAware接口，调用setBeanClassLoader()方法，传入ClassLoader对象的实例。</span><br><span class="line"></span><br><span class="line">6.如果Bean实现了BeanFactoryAware接口，调用setBeanClassFacotory()方法，传入ClassLoader对象的实例。</span><br><span class="line"></span><br><span class="line">7.与上面的类似，如果实现了其他*Aware接口，就调用相应的方法。</span><br><span class="line"></span><br><span class="line">8.如果有和加载这个Bean的Spring容器相关的BeanPostProcessor对象，执行postProcessBeforeInitialization()方法。</span><br><span class="line"></span><br><span class="line">9.如果Bean实现了InitializingBean接口，执行afeterPropertiesSet()方法。</span><br><span class="line"></span><br><span class="line">10.如果Bean在配置文件中的定义包含init-method属性，执行指定的方法。</span><br><span class="line"></span><br><span class="line">11.如果有和加载这个Bean的Spring容器相关的BeanPostProcess对象，执行postProcessAfterInitialization()方法。</span><br><span class="line"></span><br><span class="line">12.当要销毁Bean的时候，如果Bean实现了DisposableBean接口，执行destroy()方法。</span><br><span class="line"></span><br><span class="line">13.当要销毁Bean的时候，如果Bean在配置文件中的定义包含destroy-method属性，执行指定的方法。</span><br></pre></td></tr></table></figure>

<p><img src="https://img2018.cnblogs.com/blog/842514/201906/842514-20190611220522364-1747090465.png" alt="img"></p>
<p><img src="https://img2018.cnblogs.com/blog/842514/201906/842514-20190611220552139-1446928813.png" alt="img"></p>
<p>2）bean的作用域</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">1.singleton：唯一bean实例，Spring中的bean默认都是单例的。(与单例模式区别在于它是基于spring容器的，而单例是基于JVM的，多个spring容器时在JVM层面就不是单例了)</span><br><span class="line"></span><br><span class="line">2.prototype：每次请求都会创建一个新的bean实例。</span><br><span class="line"></span><br><span class="line">3.request：每一次HTTP请求都会产生一个新的bean，该bean仅在当前HTTP request内有效。</span><br><span class="line"></span><br><span class="line">4.session：每一次HTTP请求都会产生一个新的bean，该bean仅在当前HTTP session内有效。</span><br><span class="line"></span><br><span class="line">5.global-session：全局session作用域，仅仅在基于Portlet的Web应用中才有意义，Spring5中已经没有了。Portlet是能够生成语义代码（例如HTML）片段的小型Java Web插件。它们基于Portlet容器，可以像Servlet一样处理HTTP请求。但是与Servlet不同，每个Portlet都有不同的会话。</span><br></pre></td></tr></table></figure>

<p><strong>将一个类声明为Spring的bean的注解有哪些？</strong></p>
<p>我们一般使用@Autowired(由spring提供，根据类型装配，而@Resource由J2EE提供，根据名称装配)注解去自动装配bean。而想要把一个类标识为可以用@Autowired注解自动装配的bean，可以采用以下的注解实现：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">1.@Component注解。通用的注解，可标注任意类为Spring组件。如果一个Bean不知道属于哪一个层，可以使用@Component注解标注。</span><br><span class="line"></span><br><span class="line">2.@Repository注解。对应持久层，即Dao层，主要用于数据库相关操作。</span><br><span class="line"></span><br><span class="line">3.@Service注解。对应服务层，即Service层，主要涉及一些复杂的逻辑，需要用到Dao层（注入）。</span><br><span class="line"></span><br><span class="line">4.@Controller注解。对应Spring MVC的控制层，即Controller层，主要用于接受用户请求并调用Service层的方法返回数据给前端页面。</span><br></pre></td></tr></table></figure>

<h3 id="5-spring中事务"><a href="#5-spring中事务" class="headerlink" title="5.spring中事务"></a>5.spring中事务</h3><h4 id="1）管理事务的方式"><a href="#1）管理事务的方式" class="headerlink" title="1）管理事务的方式"></a>1）管理事务的方式</h4><p>​        a)声明式事务</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">声明式事务管理建立在AOP之上的。其本质是对方法前后进行拦截，然后在目标方法开始之前创建或者加入一个事务，在执行完目标方法之后根据执行情况提交或者回滚事务。声明式事务最大的优点就是不需要通过编程的方式管理事务，这样就不需要在业务逻辑代码中掺杂事务管理的代码，只需在配置文件中做相关的事务规则声明(或通过基于@Transactional注解的方式)，便可以将事务规则应用到业务逻辑中。</span><br></pre></td></tr></table></figure>



<p>​        b)编程式事务</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">编程式事务管理使用TransactionTemplate或者直接使用底层的PlatformTransactionManager。对于编程式事务管理，spring推荐使用TransactionTemplate。</span><br></pre></td></tr></table></figure>



<h4 id="2）事务隔离级别"><a href="#2）事务隔离级别" class="headerlink" title="2）事务隔离级别"></a>2）事务隔离级别</h4><p> 在TransactionDefinition接口中定义了五个表示隔离级别的常量： </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">ISOLATION_DEFAULT：使用后端数据库默认的隔离级别，Mysql默认采用的REPEATABLE_READ隔离级别；Oracle默认采用的READ_COMMITTED隔离级别。</span><br><span class="line"></span><br><span class="line">ISOLATION_READ_UNCOMMITTED：最低的隔离级别，允许读取尚未提交的数据变更，可能会导致脏读、幻读或不可重复读。</span><br><span class="line"></span><br><span class="line">ISOLATION_READ_COMMITTED：允许读取并发事务已经提交的数据，可以阻止脏读，但是幻读或不可重复读仍有可能发生</span><br><span class="line"></span><br><span class="line">ISOLATION_REPEATABLE_READ：对同一字段的多次读取结果都是一致的，除非数据是被本身事务自己所修改，可以阻止脏读和不可重复读，但幻读仍有可能发生。</span><br><span class="line"></span><br><span class="line">ISOLATION_SERIALIZABLE：最高的隔离级别，完全服从ACID的隔离级别。所有的事务依次逐个执行，这样事务之间就完全不可能产生干扰，也就是说，该级别可以防止脏读、不可重复读以及幻读。但是这将严重影响程序的性能。通常情况下也不会用到该级别。</span><br></pre></td></tr></table></figure>

<h4 id="3）事务传播行为"><a href="#3）事务传播行为" class="headerlink" title="3）事务传播行为"></a>3）事务传播行为</h4><p> 在TransactionDefinition接口中定义了八个表示事务传播行为的常量。 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">支持当前事务的情况：</span><br><span class="line"></span><br><span class="line">PROPAGATION_REQUIRED：如果当前存在事务，则加入该事务；如果当前没有事务，则创建一个新的事务。</span><br><span class="line"></span><br><span class="line">PROPAGATION_SUPPORTS： 如果当前存在事务，则加入该事务；如果当前没有事务，则以非事务的方式继续运行。</span><br><span class="line"></span><br><span class="line">PROPAGATION_MANDATORY： 如果当前存在事务，则加入该事务；如果当前没有事务，则抛出异常。（mandatory：强制性）。</span><br><span class="line"></span><br><span class="line">不支持当前事务的情况：</span><br><span class="line"></span><br><span class="line">PROPAGATION_REQUIRES_NEW： 创建一个新的事务，如果当前存在事务，则把当前事务挂起。</span><br><span class="line"></span><br><span class="line">PROPAGATION_NOT_SUPPORTED： 以非事务方式运行，如果当前存在事务，则把当前事务挂起。</span><br><span class="line"></span><br><span class="line">PROPAGATION_NEVER： 以非事务方式运行，如果当前存在事务，则抛出异常。</span><br><span class="line"></span><br><span class="line">其他情况：</span><br><span class="line"></span><br><span class="line">PROPAGATION_NESTED： 如果当前存在事务，则创建一个事务作为当前事务的嵌套事务来运行；如果当前没有事务，则该取值等价于PROPAGATION_REQUIRED。</span><br></pre></td></tr></table></figure>



<h3 id="6-springMVC"><a href="#6-springMVC" class="headerlink" title="6.springMVC"></a>6.springMVC</h3><p><img src="https://img2018.cnblogs.com/blog/842514/201906/842514-20190612121947431-1483101551.png" alt="img"></p>
<p>流程说明：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">1.客户端（浏览器）发送请求，直接请求到DispatcherServlet。</span><br><span class="line"></span><br><span class="line">2.DispatcherServlet根据请求信息调用HandlerMapping，解析请求对应的Handler。</span><br><span class="line"></span><br><span class="line">3.解析到对应的Handler（也就是我们平常说的Controller控制器）。</span><br><span class="line"></span><br><span class="line">4.HandlerAdapter会根据Handler来调用真正的处理器来处理请求和执行相对应的业务逻辑。</span><br><span class="line"></span><br><span class="line">5.处理器处理完业务后，会返回一个ModelAndView对象，Model是返回的数据对象，View是逻辑上的View。</span><br><span class="line"></span><br><span class="line">6.ViewResolver会根据逻辑View去查找实际的View。</span><br><span class="line"></span><br><span class="line">7.DispatcherServlet把返回的Model传给View（视图渲染）。</span><br><span class="line"></span><br><span class="line">8.把View返回给请求者（浏览器）。</span><br></pre></td></tr></table></figure>







<p>参考：<a href="https://www.pianshen.com/article/8686113520/" target="_blank" rel="noopener">https://www.pianshen.com/article/8686113520/</a> ioc</p>
<p><a href="https://blog.csdn.net/itcats_cn/article/details/81479185" target="_blank" rel="noopener">https://blog.csdn.net/itcats_cn/article/details/81479185</a> ioc</p>
<p><a href="https://baijiahao.baidu.com/s?id=1613310315603029991&amp;wfr=spider&amp;for=pc" target="_blank" rel="noopener">https://baijiahao.baidu.com/s?id=1613310315603029991&amp;wfr=spider&amp;for=pc</a> aop</p>
<p><a href="https://blog.csdn.net/itcats_cn/article/details/81479185" target="_blank" rel="noopener">https://blog.csdn.net/itcats_cn/article/details/81479185</a> aop</p>
<p><a href="https://www.cnblogs.com/yver/p/6027897.html" target="_blank" rel="noopener">https://www.cnblogs.com/yver/p/6027897.html</a> aop</p>
<p><a href="https://www.cnblogs.com/zq-boke/p/8515307.html" target="_blank" rel="noopener">https://www.cnblogs.com/zq-boke/p/8515307.html</a> aop</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/03/20/sublime%E5%91%BD%E4%BB%A4/" rel="next" title="sublime命令">
                <i class="fa fa-chevron-left"></i> sublime命令
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/04/01/session%E4%B8%8Ecookie%E7%9A%84%E5%8C%BA%E5%88%AB/" rel="prev" title="session与cookie的区别">
                session与cookie的区别 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">suichen</p>
              <p class="site-description motion-element" itemprop="description">记录成长</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">14</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#spring的好处："><span class="nav-number">1.</span> <span class="nav-text">spring的好处：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-Spring框架"><span class="nav-number">2.</span> <span class="nav-text">1.Spring框架</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Spring官网（https-spring-io-）列出的Spring的6个特征："><span class="nav-number">2.1.</span> <span class="nav-text">Spring官网（https:&#x2F;&#x2F;spring.io&#x2F;）列出的Spring的6个特征：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#spring框架中使用的设计模式"><span class="nav-number">2.2.</span> <span class="nav-text">spring框架中使用的设计模式</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-IOC与DI"><span class="nav-number">3.</span> <span class="nav-text">2.IOC与DI</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-AOP"><span class="nav-number">4.</span> <span class="nav-text">3.AOP</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-spring中Bean的部分知识"><span class="nav-number">5.</span> <span class="nav-text">4.spring中Bean的部分知识</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-spring中事务"><span class="nav-number">6.</span> <span class="nav-text">5.spring中事务</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1）管理事务的方式"><span class="nav-number">6.1.</span> <span class="nav-text">1）管理事务的方式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2）事务隔离级别"><span class="nav-number">6.2.</span> <span class="nav-text">2）事务隔离级别</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3）事务传播行为"><span class="nav-number">6.3.</span> <span class="nav-text">3）事务传播行为</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-springMVC"><span class="nav-number">7.</span> <span class="nav-text">6.springMVC</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">suichen</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
